package pers.qianyu.month_202103.date_20210307;

/**
 * 122. 买卖股票的最佳时机 II
 * https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-ii/
 *
 * @author mizzle rain
 * @date 2021-03-07 12:02
 */
public class MaxProfitTwo {
    public int maxProfit(int[] prices) {
        int n = prices.length;
        if (n == 0) return 0;
        // dp[i][j] 表示第 i 天，手里是否有股票的情况下的最大利润
        int[][] dp = new int[n][2];
        dp[0][0] = 0;
        dp[0][1] = -prices[0];
        for (int i = 1; i < n; i++) {
            dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][1] + prices[i]);
            dp[i][1] = Math.max(dp[i - 1][1], dp[i - 1][0] - prices[i]);
        }
        //return Math.max(dp[n - 1][0], dp[n - 1][1]);
        return dp[n - 1][0];
    }

    public int maxProfit2(int[] prices) {
        int n = prices.length;
        if (n == 0) return 0;
        int dp0 = 0, dp1 = -prices[0];
        for (int i = 1; i < n; i++) {
            int t0 = Math.max(dp0, dp1 + prices[i]);
            int t1 = Math.max(dp1, dp0 - prices[i]);
            dp0 = t0;
            dp1 = t1;
        }
        return dp0;
    }
}
